<!--
 * @Author: LiYuan
 * @Date: 2021-02-03 13:53:52
 * @LastEditTime: 2023-10-23 10:39:43
 * @LastEditors: 铃兰 wangll@publink.cn
 * @Description: 备件库存 单个 出库/入库/调拨/分配/申领
 * @You build it, You run it.
-->
<template>
  <el-dialog :title="title" :visible.sync="visible" :width="width" @close="handleClose">
    <!-- 出库 outStock -->
    <part-outstock-form v-if="visible && type === 'outStock'" ref="outstockForm" :formdata="formdata" :sparepart-config="sparepartConfig"></part-outstock-form>
    
    <!-- 入库 inStock -->
    <part-instock-form v-if="visible && type === 'inStock'" ref="instockForm" :formdata="formdata" :sparepart-config="sparepartConfig"></part-instock-form>
    
    <!-- 调拨 allocation -->
    <part-allocation-form v-if="visible && type === 'allocation'" ref="allocationForm"></part-allocation-form>

    <!-- 分配 spare -->
    <div slot="title" v-if="visible && type === 'spare'">
      <span class="el-dialog__title">{{ title }}</span>
      <p class="dialog-title-tip">
        {{ $t('part.tips5') }}
      </p>
    </div>
    <part-spares-form v-if="visible && type === 'spare'" ref="partSparesForm" :repertories="repertories" :formdata="formdata" :repertory="repertory"></part-spares-form>
        
    <!-- 申领 apply -->
    <part-apply-form v-if="visible && type === 'apply'" ref="applyForm" :formdata="formdata" :sparepart-config="sparepartConfig"></part-apply-form>
    
    <!-- footer -->
    <div slot="footer" class="dialog-footer">
      <el-button type="ghost" @click="visible = false" >{{ $t('common.paas.buttons.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="pending"  :loading="pending" v-if="isShowConfirmBtn">{{ $t('common.base.makeSure') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import PartOutStockForm from '../form/PartOutStockForm.vue';
import PartInStockForm from '../form/PartInStockForm.vue';
import PartAllocationForm from '../form/PartAllocationForm.vue';
import PartSparesForm from '../form/PartSparesForm.vue';
import PartApplyForm from '../form/PartApplyForm.vue';
import { debounce } from 'lodash';
import { t } from '@src/locales' 
export default {
  name: 'stock-single-opt-dialog',
  components: {
    [PartOutStockForm.name]: PartOutStockForm,
    [PartInStockForm.name]: PartInStockForm,
    [PartAllocationForm.name]: PartAllocationForm,
    [PartSparesForm.name]: PartSparesForm,
    [PartApplyForm.name]: PartApplyForm,
  },
  props: {
    width: {
      type: String,
      default: "600px"
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ""
    },
    // 目前只在分配用到
    repertories: {
      type: Array,
      default: () => []
    },
    // 目前只在分配用到
    repertory: {
      type: Array,
      default: () => []
    },
    formdata: {
      type: Object,
      default: () => { }
    },
    sparepartConfig: {
      type: Object,
      default: () => { }
    }
  },
  data: () => {
    return {
      visible: false,
      pending: false,
      titleMap: {
        'outStock': t('part.text4'),
        'inStock': t('part.text5'),
        'allocation': t('part.text6'),
        'spare': t('part.text7'),
        'apply': t('part.text8'),
      }
    }
  },
  watch: {
    dialogVisible: {
      handler(val) {
        this.visible = val
      },
      immediate: true
    }
  },
  computed: {
    title() {
      return this.type ? this.titleMap[this.type] : ''
    },
    isShowConfirmBtn() {
      if ((this.type === 'outStock' || this.type === 'inStock') && !this.sparepartConfig) {
        return false
      } else {
        return true
      }
    }
  },
  methods: {
    // 弹窗关闭
    handleClose() {
      this.$emit('close')
    },
    
    // 确认
    handleConfirm: debounce(function(){
      switch (this.type) {
        case 'outStock':
          this.outstockSave()
          break;
        case 'inStock':
          this.instockSave()
          break;
        case 'allocation':
          this.allocationSave()
          break;
        case 'spare':
          this.partSparesSave()
          break;
        case 'apply':
          this.applySave()
          break;
        default:
          break;
      }
    },500),

    // 调拨备件初始化
    allocationFormInit (value, repertory ,sparepartConfig, userId) {
      this.$nextTick(() => {
        this.$refs.allocationForm.init(value, repertory, sparepartConfig, userId)
      })
    },

    // 出库（单次）
    async outstockSave(){
      let form = this.$refs.outstockForm;
      if(null == form) return;
      let outstock = await form.pack();
      if(null == outstock) return;
      this.pending = true;
      try {
        let result = await this.$http.post('/partV2/repertory/stockInOut', outstock);
        if(result.status == 0){
          this.$platform.toast(t('part.tips12')).then(() => this.$emit('success'));
          this.handleClose()
        }else{
          this.$platform.alert(result.message);
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.pending = false;
      }
    },

    // 入库（单次）
    async instockSave(){
      let form = this.$refs.instockForm;
      if(null == form) return;
      let instock = await form.pack();
      if(null == instock) return;
      this.pending = true;
      try {
        let result = await this.$http.post('/partV2/repertory/stockInOut', instock);
        if(result.status == 0){
          this.$platform.toast(t('part.tips13')).then(() => this.$emit('success'));
          this.handleClose()
        }else{
          this.$platform.alert(result.message);
        }

      } catch (error) {
        console.log(error)
      } finally {
        this.pending = false;
      }
    },

    // 调拨
    async allocationSave(){
      let form = this.$refs.allocationForm;
      if(null == form) return;
      let allocation = await form.pack();
      if(null == allocation) return;
      this.pending = true;
      try {
        let result = await this.$http.post('/partV2/approve/transfer/initiate', allocation);
        if(result.status == 0){
          this.$platform.toast(`${result.data ? t('part.tips14') : t('part.tips15')}`).then(() => this.$emit('success'));
          this.handleClose()
        }else{
          this.$platform.alert(result.message);
        }

      } catch (error) {
        console.log(error)
      } finally {
        this.pending = false;
      }
    },

    // 分配  (单次)
    async partSparesSave() {

      let form = this.$refs.partSparesForm;
      if (!form) return;

      let partSparesData = form.pack();
      if (!partSparesData) return;
      
      this.pending = true;

      let params = {
        repertoryId: partSparesData.repertoryId,
        sparepartId: partSparesData.sparepartId,
        variation: partSparesData.sparesNum,
        remark: partSparesData.remarks,
        targetId: partSparesData.repertory,
      }
      try {
        let result = await this.$http.post('/partV2/approve/allot/initiate', params);
  
        if((result && result.status === 0)){

          this.$platform.toast(t('part.tips16')).then(() => this.$emit('success'));
          this.handleClose()

        }else{
          this.$platform.alert(result.message);
        }
      } catch (e) {
        console.warn(e);
      } finally {
        this.pending = false;
      }
    },

    // 申领
    async applySave(){
      let form = this.$refs.applyForm;
      if(null == form) return;
      let apply = await form.pack();
      if(null == apply) return;
      this.pending = true;
      try {
        let result = await this.$http.post('/partV2/approve/apply', apply);
        if(result.status == 0){
          this.$platform.toast(t('part.tips17')).then(() => this.$emit('success'));
          this.handleClose()
        }else{
          this.$platform.alert(result.message);
        }

      } catch (error) {
        console.log(error)
      } finally {
        this.pending = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog {
    .el-dialog__header {
      padding: 10px 15px 10px 20px;
      .el-dialog__headerbtn {
        right: 0;
      }
      .el-dialog__title {
        color: #262626;
      }
    }
    .el-dialog__body {
      padding: 10px 15px 10px 25px;
      height: 380px;
      overflow: auto;
      .el-form-item {
        &:not(.form-tips-item) {
          margin: 0;
          &:not(:first-child) {
            margin-top: 12px;
          }
        }
        &.form-tips-item {
          margin: 0;
          line-height: 20px;
        }
      }
    }
  }
  ::v-deep .el-dialog__footer {
    padding: 6px 6px 12px 6px;
  }
</style>